using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcContrib.EnumerableExtensions;
using MvcContrib.Pagination;
using OnlineExam.Entities;
using OnlineExam.Models;

namespace OnlineExam.Controllers
{   
    public class UsersController : Controller
    {
		private readonly IUserRepository userRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public UsersController() : this(new UserRepository())
        {
        }

        public UsersController(IUserRepository userRepository)
        {
			this.userRepository = userRepository;
        }

        //
        // GET: /Users/

        public ViewResult Index(int? page)
        {
			var model = userRepository.GetAll(user => user.Attendances, user => user.Posts, user => user.UserMetas);
            return View(model.AsPagination(page ?? 1, Config.GetInt("PageSize")));
        }

        //
        // GET: /Users/Details/5

        public ViewResult Details(int id)
        {
			var model = userRepository.Single(t=>t.ID == id);
            return View(model);
        }

        //
        // GET: /Users/Create

        public ActionResult Create()
        {
			var model = new User();
            return View(model);
        } 

        //
        // POST: /Users/Create

        [HttpPost]
        public ActionResult Create(User model)
        {
            if (ModelState.IsValid) {
                userRepository.Insert(model);
                userRepository.Save();
                return RedirectToAction("Index");
            } else {
				return View(model);
			}
        }
        
        //
        // GET: /Users/Edit/5
 
        public ActionResult Edit(int id)
        {
			var model = userRepository.Single(t=>t.ID == id);
             return View(model);
        }

        //
        // POST: /Users/Edit/5

        [HttpPost]
        public ActionResult Edit(User model)
        {
            if (ModelState.IsValid) {
                userRepository.Update(model);
                userRepository.Save();
                return RedirectToAction("Index");
            } else {
				return View(model);
			}
        }

        //
        // GET: /Users/Delete/5
 
        public ActionResult Delete(int id)
        {
			var model = userRepository.Single(t=>t.ID == id);
            return View(model);
        }

        //
        // POST: /Users/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
			var model = userRepository.Single(t=>t.ID == id);
            userRepository.Delete(model);
            userRepository.Save();

            return RedirectToAction("Index");
        }
    }
}

